#include "ComponentUdder.h"
#include "ComponentHerdBehavior.h"

#include "Components/ComponentMiner.h"
#include "Components/ComponentCreature.h"
#include "Subsystems/SubsystemTimeOfDay.h"
#include "Subsystems/SubsystemGameInfo.h"

#include "GameRandom.hpp"
#include "Engine/MathUtils.hpp"
#include "Log.h"

#include "GameSingleton.h"
#include "GameRegistry.hpp"
#include "GameThreadPool.hpp"

#include <iostream>

namespace PocketSurvival
{

    bool ComponentUdder::hasMilk()
    {
        if (m_lastMilkingTime >= 0.0)
        {
            return gameInfo->totalElapsedGameTime - m_lastMilkingTime >= m_milkRegenerationTime;
        }
        return true;
    }

    bool ComponentUdder::Milk(ComponentMiner *milker)
    {
        if (milker != nullptr && herdBehavior != nullptr)
        {
            herdBehavior->callNearbyCreaturesHelp(milker->entity, 20.0f, 20.0f, true);
        }
        if (hasMilk())
        {
            // 播放声音
            m_lastMilkingTime = gameInfo->totalElapsedGameTime;
            return true;
        }
        // 播放声音
        return false;
    }

    static const std::string componentName = "Udder";
    const std::string &ComponentUdder::getName() const
    {
        return componentName;
    }
    const std::string &ComponentUdder::GetName()
    {
        return componentName;
    }

    void ComponentUdder::load(const nlohmann::json &jsonData)
    {
        componentCreature    = GameSingleton::gameRegistry->get<ComponentCreature *>(entity);
        ComponentHerdBehavior **herdPtr = GameSingleton::gameRegistry->try_get<ComponentHerdBehavior*>(entity);
        herdBehavior = (herdPtr != nullptr) ? *herdPtr : nullptr;

        timeOfDay = GameSingleton::singletonPtr->getSingleton<SubsystemTimeOfDay>();
        gameInfo = GameSingleton::singletonPtr->getSingleton<SubsystemGameInfo>();

        m_milkRegenerationTime = jsonData["MilkRegenerationTime"].get<float>();
        m_lastMilkingTime = jsonData["LastMilkingTime"].get<float>();
    }

    void ComponentUdder::save(nlohmann::json &jsonData)
    {
        jsonData["LastMilkingTime"] = m_lastMilkingTime;
    }

}
